package dbops

import (
	_ "database/sql"
	"gitee.com/DengAnbang/Wefore/src/bean"
	"gitee.com/DengAnbang/goutils/dbutils"
	"gitee.com/DengAnbang/goutils/loge"
	"gitee.com/DengAnbang/goutils/utils"
)

type StructureTreeBean struct {
	bean.TreeBean
	HeadUserId   string `json:"head_user_id"`
	HeadUserName string `json:"head_user_name"`
}

func NewStructureTreeBean(data map[string]string) StructureTreeBean {
	return StructureTreeBean{
		TreeBean:     bean.NewTreeBean(data),
		HeadUserId:   data["head_user_id"],
		HeadUserName: data["name"],
	}
}

func StructureTreeNodeCreate(userId, nodeName, nodeParentId string) (StructureTreeBean, error) {
	var treeBean = StructureTreeBean{}
	treeBean.NodeName = nodeName
	treeBean.NodeParentId = nodeParentId
	var depth = 0
	if len(userId) == 0 {
		return treeBean, bean.NewErrorMessage("创建人ID不能为空")
	}
	if len(nodeName) == 0 {
		return treeBean, bean.NewErrorMessage("名称不能为空")
	}
	//pass, err := PermissionInspection(userId, nodeParentId)
	//if err != nil {
	//	return treeBean, err
	//}
	//if !pass {
	//	return treeBean, bean.NewErrorMessage("没有权限!")
	//}
	if len(nodeParentId) == 0 {
		nodeParentId = "0"
	} else {
		treeParentBean, err := StructureTreeNodeSelect(nodeParentId)
		if err != nil {
			return treeBean, err
		}
		depth = treeParentBean.Depth + 1
	}
	uuid := utils.NewUUID()
	stmtIn, err := dbConn.Prepare("INSERT INTO table_tree_structure (node_id,node_name,node_parent_id,depth)VALUES(?,?,?,?)")
	if err != nil {
		return treeBean, err
	}
	_, err = stmtIn.Exec(uuid, nodeName, nodeParentId, depth)
	if err != nil {
		return treeBean, err
	}
	stmtIn.Close()
	treeBean.Depth = depth
	treeBean.NodeId = uuid
	loge.WD(bean.NewSucceedMessage(treeBean).GetJson())
	return treeBean, nil
}

//todo 递归删除(待优化)
func StructureTreeNodeDelete(nodeId string) error {

	if len(nodeId) == 0 {
		return bean.NewErrorMessage("节点ID不能为空")
	}
	if nodeId == "0" {
		return bean.NewErrorMessage("根节点不能为删除！")
	}
	beans, err := StructureTreeChildNodeSelectAll(nodeId)
	if err != nil {
		return err
	}
	beans = append(beans, StructureTreeBean{TreeBean: bean.TreeBean{NodeId: nodeId}})
	for _, v := range beans {
		stmtIn, err := dbConn.Prepare("DELETE FROM table_tree_structure WHERE node_id=?")
		if err != nil {
			return err
		}
		_, err = stmtIn.Exec(v.NodeId)
		if err != nil {
			return err
		}
		stmtIn.Close()
		stmtIn, err = dbConn.Prepare("DELETE FROM table_tree_structure_permission WHERE node_id=?")
		if err != nil {
			return err
		}
		_, err = stmtIn.Exec(v.NodeId)
		stmtIn.Close()
	}

	return err
}
func StructureTreeNodeUpdate(nodeId, nodeName, headUserId string) error {
	if len(nodeId) == 0 {
		return bean.NewErrorMessage("节点ID不能为空")
	}
	treeBean, _ := StructureTreeNodeSelect(nodeId)
	if len(nodeName) != 0 {
		treeBean.NodeName = nodeName
	}
	if len(headUserId) != 0 {
		treeBean.HeadUserId = headUserId
	}
	stmtIn, err := dbConn.Prepare("UPDATE  table_tree_structure SET node_name=?,head_user_id=? WHERE node_id=?")
	if err != nil {
		return err
	}
	_, err = stmtIn.Exec(treeBean.NodeName, treeBean.HeadUserId, nodeId)
	if err != nil {
		return err
	}
	_ = stmtIn.Close()
	return err
}

//查询单个树节点的信息
func StructureTreeNodeSelect(nodeId string) (StructureTreeBean, error) {
	var structureBean StructureTreeBean
	stmtOut, err := dbConn.Prepare("SELECT * FROM table_tree_structure WHERE node_id = ?")
	if err != nil {
		return structureBean, err
	}
	defer stmtOut.Close()
	rows, err := stmtOut.Query(nodeId)
	if err != nil {
		return structureBean, err
	}
	defer rows.Close()
	if rows.Next() {
		var stringMap map[string]string
		stringMap, err = dbutils.GetRowsMap(rows)
		if err != nil {
			return structureBean, err
		}
		structureBean = NewStructureTreeBean(stringMap)
	}
	return structureBean, err
}

//查询当级所有子节点树节点的信息
func StructureTreeChildNodeSelect(nodeId string) ([]StructureTreeBean, error) {
	var structureBean = make([]StructureTreeBean, 0)
	stmtOut, err := dbConn.Prepare("SELECT * FROM table_tree_structure LEFT OUTER JOIN table_user ON table_tree_structure.head_user_id=table_user.user_id WHERE node_parent_id = ?")
	if err != nil {
		return structureBean, err
	}
	defer stmtOut.Close()
	rows, err := stmtOut.Query(nodeId)
	if err != nil {
		return structureBean, err
	}
	defer rows.Close()
	for rows.Next() {
		var stringMap map[string]string
		stringMap, err = dbutils.GetRowsMap(rows)
		if err != nil {
			return structureBean, err
		}
		structureBean = append(structureBean, NewStructureTreeBean(stringMap))
	}
	return structureBean, err
}

//查询所有子节点树节点的信息
func StructureTreeChildNodeSelectAll(nodeId string) ([]StructureTreeBean, error) {
	//使用递归的方法
	_, err := dbConn.Exec(`DROP FUNCTION IF EXISTS get_child_list_table_tree_structure ;`)
	_, err = dbConn.Exec(`
CREATE FUNCTION  get_child_list_table_tree_structure(rootId VARCHAR(64))
 RETURNS VARCHAR(1000)
DETERMINISTIC
 BEGIN
   DECLARE sTemp VARCHAR(1000);
   DECLARE sTempChd VARCHAR(1000);
   SET sTemp = '$';
   SET sTempChd = cast(rootId AS CHAR);
   WHILE sTempChd IS NOT NULL DO
     SET sTemp = concat(sTemp, ',', sTempChd);
     SELECT group_concat(node_id)
     INTO sTempChd
     FROM table_tree_structure
     WHERE FIND_IN_SET(node_parent_id, sTempChd) > 0 ;
   END WHILE;
   RETURN sTemp;
 END`)
	var structureBean = make([]StructureTreeBean, 0)
	if err != nil {
		return structureBean, err
	}
	stmtOut, err := dbConn.Prepare("SELECT * FROM table_tree_structure LEFT OUTER JOIN table_user ON table_tree_structure.head_user_id=table_user.user_id WHERE  FIND_IN_SET(node_id, get_child_list_table_tree_structure(?))")
	if err != nil {
		return structureBean, err
	}
	defer stmtOut.Close()
	rows, err := stmtOut.Query(nodeId)
	if err != nil {
		return structureBean, err
	}
	defer rows.Close()
	for rows.Next() {
		var stringMap map[string]string
		stringMap, err = dbutils.GetRowsMap(rows)
		if err != nil {
			return structureBean, err
		}
		if nodeId == stringMap["node_id"] {
			continue
		}
		structureBean = append(structureBean, NewStructureTreeBean(stringMap))
	}
	return structureBean, err
}

////查询所有子节点树节点的信息
////递归查询
//func StructureTreeChildNodeSelectAll(nodeId, RisProject string) ([]TreeBean, error) {
//	//使用递归的方法
//	var treeBean = make([]TreeBean, 0)
//	beans, err := StructureTreeChildNodeSelect(nodeId)
//	if err != nil {
//		return treeBean, err
//	}
//	treeBean = append(treeBean, beans...)
//	for _, v := range beans {
//		if isProject == "1" && v.IsProject == isProject {
//			continue
//		}
//		treeBeans, err := StructureTreeChildNodeSelectAll(v.NodeId, isProject)
//		if err != nil {
//			return treeBeans, err
//		}
//		treeBean = append(treeBean, treeBeans...)
//	}
//	return treeBean, err
//
//}
